<?php

namespace addons\wxfollowlogin\controller;

use addons\wxfollowlogin\model\Wxfollowlogin;
use addons\wxfollowlogin\model\WxfollowloginScene;
use EasyWeChat\Factory;
use think\addons\Controller;
use think\Config;
use think\Cookie;
use think\Hook;

class Index extends Controller
{

    public function _initialize()
    {
        parent::_initialize();
        $auth = $this->auth;

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

        //监听注册登录注销的事件
        Hook::add('user_login_successed', function ($user) use ($auth) {
            $expire = input('post.keeplogin') ? 30 * 86400 : 0;
            Cookie::set('uid', $user->id, $expire);
            Cookie::set('token', $auth->getToken(), $expire);
        });
        Hook::add('user_register_successed', function ($user) use ($auth) {
            Cookie::set('uid', $user->id);
            Cookie::set('token', $auth->getToken());
        });
        Hook::add('user_delete_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
        Hook::add('user_logout_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
    }


    /**
     * 二维码显示页面
     * @return mixed
     * @throws \think\Exception
     */
    public function index()
    {
        $config = get_addon_config('wxfollowlogin');
        $option = [
            'app_id' => $config['appid'],
            'secret' => $config['appsecret'],
            'token' => $config['token'],
            'aes_key' => $config['encodingaeskey'],
            'response_type' => 'array',
        ];
        $mpType = $config['mptype'];
        $mpErcode = $config['mpercode'];

        $app = Factory::officialAccount($option);

        $client_id = $this->get_client_ip();

        //限制ip一段时间内的访问次数
        $sceneModel = new WxfollowloginScene();
        $senceCount = $sceneModel->where(['ip' => $client_id, 'createtime' => ['gt', time() - 60]])->count();
        if ($senceCount > 10) {
            $this->error('访问次数太频繁，请稍后再试~');
        }

        //删除三天以前的sence记录
        $sceneModel = new WxfollowloginScene();
        $sceneModel->where(['createtime' => ['lt', 60 * 60 * 24 * 3]])->delete();

        //生成sence
        if($mpType == "auth"){
            $rand = md5(date("ymdhis") . rand(10000, 99999));      //生成随机sence
        }else{
            $rand = rand(100000, 999999);      //生成随机sence
        }

        $sceneModel = new WxfollowloginScene();
        $sceneModel->save(array('ip' => $client_id, 'scene_id' => $rand));

        $ticket_img = "";
        if($mpType == "auth"){
            $return = $app->qrcode->temporary($sceneModel->id, 6 * 24 * 3600);
            if (!empty($return['ticket'])) {
                $ticket_img = $app->qrcode->url($return['ticket']);
            }
        }else{
            $ticket_img = $mpErcode;
        }

        $this->assign('scene_id', $rand);
        $this->assign('mpType',$mpType);
        $this->assign('ticket_img', $ticket_img);
        $this->assign("url","");
        return $this->fetch();
    }

    /**
     * 获取请求IP
     * @return mixed
     */
    private function get_client_ip()
    {
        $ip = $_SERVER['REMOTE_ADDR'];
        if (isset($_SERVER['HTTP_CLIENT_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR']) AND preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) {
            foreach ($matches[0] AS $xip) {
                if (!preg_match('#^(10|172\.16|192\.168)\.#', $xip)) {
                    $ip = $xip;
                    break;
                }
            }
        }
        return $ip;
    }


    /**
     * 定时获取扫码结果
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function scan()
    {
        $scene_id = $this->request->post("scene_id");
        $sceneModel = new WxfollowloginScene();
        $scene = $sceneModel->where(['scene_id' => $scene_id,'createtime'=>['gt',time()-60]])->find();
        if (!empty($scene['openid'])) {
            $followUser = Wxfollowlogin::get(['openid' => $scene['openid']]);
            //写入登录Cookies和Token
            $this->auth->direct($followUser->user_id);
            echo json_encode(array('code' => 0, 'data' => array('openid' => $scene['openid'])));
        } else {
            echo json_encode(array('code' => 1, 'data' => array('openid' => '')));
        }
        return null;
    }

}
